/*
 * ItemRoutingRateResource.cpp
 *
 *  Created on: 2014. 3. 5.
 *      Author: mega
 */

#include <algorithm>
#include <Toolkit/Str.h>
#include <Database/Static.h>
#include "ItemRoutingRateResource.h"
#include "../macro.h"

namespace ProjectZ { namespace NResource {

ItemRoutingRateResource::ItemRoutingRateResource()
{
	totalRate = 0;
}

ItemRoutingRateResource::~ItemRoutingRateResource()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](ITEMROUTINGRATETREE::value_type & pair) {
		delete pair.second;
	});
}

void
ItemRoutingRateResource::Clear()
{
	totalRate = 0;

	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](ITEMROUTINGRATETREE::value_type & pair) {
		delete pair.second;
	});
	clsFlyTree.clear();
}

int
ItemRoutingRateResource::GetTotalRate()
{
	return totalRate;
}

ItemRoutingRateResource::ITEMROUTINGRATETREE &
ItemRoutingRateResource::GetTree()
{
	return clsFlyTree;
}

bool
ItemRoutingRateResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT * FROM resource_item_routing_rate");

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		Toolkit::Str<30> DESC;
		Flyweight * pFly = new Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_EFFECT_TYPE >> pFly->_QUALITY1 >> pFly->_QUALITY2 >> pFly->_QUALITY3
				>> pFly->_QUALITY4 >> pFly->_QUALITY5 >> pFly->_QUALITY6 >> pFly->_QUALITY7
				>> pFly->_QUALITY8 >> pFly->_QUALITY9 >> pFly->_QUALITY10
				>> pFly->_VALUE_TYPE >> pFly->_LEVEL_CONST >> pFly->_OVER_A_TYPE >> pFly->_RATE >> DESC;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		if (1 == pFly->_OVER_A_TYPE)
		{
			totalRate += pFly->_RATE;
		}

		clsFlyTree[pFly->_EFFECT_TYPE] = pFly;
	}

	if (1000 != totalRate)
	{
		PROCESSLOG("%s : Oops!! Rate is not equal 1000!!!", __FUNCTION__);
		return false;
	}

	return true;
}

ItemRoutingRateResource::Flyweight *
ItemRoutingRateResource::GetFly(int effectType)
{
	auto iter = clsFlyTree.find(effectType);
	if (iter == clsFlyTree.end())
		return NULL;

	return iter->second;
}

} /*NResource*/ } /*ProjectZ*/
